package com.wonders;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Iterator;
import java.util.List;

/**
 * 更多可参考：
 * http://commons.apache.org/proper/commons-fileupload/using.html
 * https://www.cnblogs.com/xdp-gacl/p/4200090.html
 */
@WebServlet("/UploadServletJar")
public class UploadServletJar extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 单例配置工厂类
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);


        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();  // 迭代form表单的每一个字段
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (!item.isFormField()) {
                    String contextPath = request.getServletContext().getRealPath("/");
                    File uploadedFile = new File(contextPath + item.getName());
                    item.write(uploadedFile);
                } else {
                    System.out.println(item.getFieldName() + "===" + item.getString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
